<template>
  <div class="layer-box">
    
    
    <div id="container" ref="layerRef">
      <div
        :ref="(el) => { if (el) setItemRef(el, item) }"
        v-for="(item) in layerList.filter(item => item.show)" 
        :key="item.index"
        class="item"
        :style="{
          width: `${config.itemWidth}px`,
          height: `${config.itemHeight}px`,
          left: `${item.left}px`,
          top: `${item.top}px`
        }"
      >
        <div class="item-header">
          <div>{{ item.name }}</div>
          <div @click="removeRandomItem(item)" class="x-icon"></div>
        </div>
        <div class="item-content">
          <div>
            位置: ({{ item.offsetX }}, {{ item.offsetY }})
            <div><solt :data="item.data">数据：{{ item.data }}</solt></div>
          </div>
        </div>
      </div>
    </div>
    <div class="controls">
      <button @click="addItem">添加图框</button>
      <button @click="reset">重置</button>
      <div class="stats">{{ statsText }}</div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick, defineEmits } from 'vue';
import { domMouseDrag } from "../../tool.js";
export default {
  setup(props, context) {
    // 配置参数
    const config = {
      containerWidth: 1000,
      containerHeight: 900,
      itemWidth: 240,
      itemHeight: 250,
      startX: 20,
      startY: 20,
      maxItems: 45
    };
    // 状态变量
    const layerRef = ref()
    const layerItemRefs = ref([])
    const currentPage = ref(1);
    const currentRow = ref(1);
    const currentCol = ref(1)

    const layerList = ref([])


    // 计算行列数和间距
    const calculateLayout = () => {
      // 列显示数量
      const colNumber = Math.floor((config.containerWidth - config.startX * 2) / config.itemWidth);

      // 行显示数量
      const rowNumber = Math.floor((config.containerHeight - config.startY * 2) / config.itemHeight);

      // 列每两个间距
      const colSpace = colNumber === 1 ? 0 : Math.floor(
        (config.containerWidth - colNumber * config.itemWidth - 40) / (colNumber - 1)
      );
      
      // 行每两个间距
      const rowSpace = rowNumber===1 ? 0 : Math.floor(
        (config.containerHeight - rowNumber * config.itemHeight - 40) / (rowNumber - 1)
      );
      console.log(rowSpace)
      return { colNumber, rowNumber, colSpace, rowSpace };
    };
    
    let colNumber, rowNumber, colSpace, rowSpace, cols, rows
    
    // 添加图框
    const addItem = (item) => {
      if (layerList.value.length >= config.maxItems) {
        alert(`最多只能添加 ${config.maxItems} 个图框`);
        return;
      }
      
      let history = layerList.value.find(item => !item.show);
      if (history) {
        history.show = true;
        history.top = history.offsetY
        history.left = history.offsetX;
        history.centerX = history.offsetX1 + config.itemWidth / 2,
        history.centerY = history.offsetY1 + config.itemHeight / 2,
        history.data = item || '新的数据'
      } else {
        const name = `图框-${layerList.value.length}`;
        let offsetX1 = (currentPage.value * config.startX) 
          + (config.itemWidth + colSpace) * (currentCol.value - 1)
        let offsetY1 = (currentPage.value * config.startY) 
          + (config.itemHeight + rowSpace) * (currentRow.value - 1)
        console.log(config.itemHeight )
        layerList.value.push({
          show: true,
          index: layerList.value.length,
          offsetX: offsetX1,
          offsetY: offsetY1,
          top: offsetY1,
          left: offsetX1,
          centerX: offsetX1 + config.itemWidth / 2,
          centerY: offsetY1 + config.itemHeight / 2,
          data: item || '初始数据',
          name
        })
        
        
        // 换列处理
        if (currentCol.value === colNumber) {
          currentCol.value = 1;
          if (currentRow.value === rowNumber) {
            currentRow.value = 1
            currentPage.value++;
            // layerRef.value.style.transform = `scale(${(config.containerWidth * 1.0 ) / (config.containerWidth + (currentPage.value - 1) * config.startX)});`
            // console.log(`scale(${(config.containerWidth * 1.0 )/ (config.containerWidth + (currentPage.value - 1) * config.startX)});`)
          } else {
            currentRow.value++;
          }
        } else {
          currentCol.value++;
          if (cols.includes(currentCol.value) && rows.includes(currentRow.value)) {
            currentCol.value += cols.length
          }
        }
      }
      context.emit("change", layerList.value.filter(item => item.show))
    };
    
    const setItemRef = (el, item) => {
      if (el) {
        layerItemRefs.value[item.index] = el;  // 确保元素正确存储
        domMouseDrag(el, layerRef.value, (val) => {
          item.top = val.top
          item.left = val.left
          item.centerX = val.centerX
          item.centerY = val.centerY
          console.log(val)
          context.emit("change", layerList.value.filter(item => item.show))

        })
      }
    };
    // 随机移除图框
    const removeRandomItem = ({index}) => {
      console.log(layerList.value)
      layerList.value[index].show = false
      layerList.value[index].data = "移除"
      context.emit("change", layerList.value.filter(item => item.show))
    };

    const removeItemByKey = (key, value) => {
      const index = layerList.value.findIndex(item => item.data[key] === value)
      if (index > -1) {
        layerList.value[index].show = false
        layerList.value[index].data = "移除"
      }
    }
    
    // 重置
    const reset = () => {
      layerList.value = []
      currentPage.value = 1;
      currentRow.value = 1;
      currentCol.value = 1
      context.emit("change", layerList.value)
    };
    
    // 统计信息
    const statsText = computed(() => {
      return `
        当前图框数: ${layerList.value.length} | 
        空闲位置数: (${layerList.value.filter(i => !i.show).length}个) | 
        页: ${currentPage.value} | 行: ${currentRow.value} | 列：${currentCol.value}
      `;
    });
    
    // 初始添加几个图框
    onMounted(() => {
      let {width,height } = layerRef.value.getBoundingClientRect()
      config.containerWidth = width
      config.containerHeight = height
      let calculate = calculateLayout();
      rowNumber = calculate.rowNumber
      colNumber = calculate.colNumber
      colSpace = calculate.colSpace
      rowSpace = calculate.rowSpace

      let nullObj = handleNull(colNumber, rowNumber)
      console.log(handleNull(colNumber, rowNumber))
      cols = nullObj.cols
      rows = nullObj.rows

      
      // for (let i = 0; i < 5; i++) {
      //   addItem();
      // }
    });

    function handleNull(colNum, rowNum) {
      console.log(colNum, rowNum)
      let cols = []
      let rows = []
      if (colNum > 2 && rowNum > 2) {
        if (colNum % 2 === 1) {
          cols = [parseInt(colNum / 2) + 1]
        } else {
          cols = [parseInt(colNum / 2), parseInt(colNum / 2) + 1]
        }
        if (rowNum % 2 === 1) {
          rows = [parseInt(rowNum / 2) + 1]
        } else {
          rows = [parseInt(rowNum / 2), parseInt(rowNum / 2) + 1]
        }
      }
      return {
        cols,
        rows
      }
    }
    
    return {
      config,
      layerList,
      addItem,
      removeRandomItem,
      removeItemByKey,
      reset,
      setItemRef,
      statsText,
      layerRef
    };
  }
};
</script>

<style lang="less">
.layer-box{
  position: absolute;
  top:0;
  left: 0;
  right:0;
  bottom: 0;
  pointer-events: none;   /* 允许鼠标事件穿透到下层元素 */
  overflow: hidden;
}
#container {
  position: relative;
  width: 100%;
  height: 100%;
  border: 2px solid #ccc;
  box-sizing: border-box;
  .item {
    position: absolute;
    border: 1px solid #3498db;
    background-color: #f8f9fa;
    border-radius: 5px;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    pointer-events: auto;
  }
}



.item-header {
  font-weight: bold;
  margin-bottom: 5px;
  color: #2c3e50;
  display: flex;
  justify-content: space-between;
}

.item-content {
  flex: 1;
  background-color: #ecf0f1;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #7f8c8d;
}

.controls {
  display: flex;
  gap: 10px;
  background-color: #f8f9fa;
  pointer-events: auto;
  position: absolute;
  top:0;
}

button {
  padding: 8px 15px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #2980b9;
}

.stats {
  margin-top: 10px;
  font-size: 14px;
  color: #555;
}

.x-icon {
  position: relative;
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.x-icon::before,
.x-icon::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #000;
}

.x-icon::before {
  transform: rotate(45deg);
}

.x-icon::after {
  transform: rotate(-45deg);
}
</style>